<?php
namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\AdminUser;
use think\Db;
use think\Session;

/**
 * 权限管理控制器
 * 添加权限 addAuto
 * 权限列表 autoList
*/
class Restrict extends CommonController
{
	public function autoList()
	{
		// 获取当前userid
		$userid = Session::get('userId');

		if ($userid==1) 
		{
           $sql='select * from Adminnode';

           $data=Db::query($sql);
       	}
        else
        {
			$sql="select distinct(nodeName),rn.nodeId,u.userId,nodeController,nodeAction,nodePid from Adminuser u
	              inner join userrole ur on u.userId = ur.userId
	              inner join Adminrole r on r.roleId = ur.roleId
	              inner join rolenode  rn on r.roleId = rn.roleId
	              inner join Adminnode n on n.nodeId = rn.nodeId
	              where u.userId =$userid";

	        $data=Db::query($sql);
    	}
       	$info = $this->digui($data);

       	return $this->fetch('list',['info'=>$info]);
	}
	/*权限添加*/
	public function addAuto()
	{
		if (Request::instance()->isPost())
		{
			$data=Request::instance()->post(false);

			$res=Db::name('Adminnode')->insert($data);

			if ($res) 
			{
				$this->success('添加成功','restrict/list');
			}
		}
		else
		{
			$arr=Db::table('Adminnode')->where('nodePid','=','0')->select();

			return $this->fetch('add',['info'=>$arr]);
		}
	}
	//递归
	public function digui($arr,$parent_id=0,$level=0)
	{
		GLOBAL $data;

		foreach ($arr as $k => $v) 
		{
			if ($v['nodePid']==$parent_id) 
			{
				$v['level']=$level;
				$data[]=$v;
				$this->digui($arr,$v['nodeId'],$level+1);
			}
		}
		return $data;
	}
}